﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Media.Effects;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using System.Diagnostics;
using System.Net;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
using System.ComponentModel;
using WF = System.Windows.Forms;
using System.Xml;

namespace UpdateClient
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private string ApplicationName = "JustPlus";//更新的应用程序名称
        private string filepath = "";//下载文件的临时存放路径
        private string currentfilepath = System.Windows.Forms.Application.StartupPath;
        private string newversion = "";
        private string newdate = "";
        public static WF.NotifyIcon notifyIcon = null;

        public MainWindow()
        {
            InitializeComponent();
            this.Width = 512;
            this.Height = 256;

            notifyIcon = new WF.NotifyIcon();
            notifyIcon.Text = "JustListen更新程序";

            System.Drawing.Icon icon = new System.Drawing.Icon(@"updatelogo.ico");
            notifyIcon.Icon = icon;
            notifyIcon.Visible = true;

            this.Loaded += new RoutedEventHandler(UpdateWnd_Loaded);
            notifyIcon.MouseClick += new System.Windows.Forms.MouseEventHandler(notifyIcon_MouseClick);
            WF.MenuItem[] menuitems = new WF.MenuItem[2];
            menuitems[0] = new WF.MenuItem("打开主界面", new EventHandler(open_MainPanel));
            menuitems[1] = new WF.MenuItem("取消更新", new EventHandler(exit));
            WF.ContextMenu childen = new WF.ContextMenu(menuitems);
            notifyIcon.ContextMenu = childen;
        }

        private void open_MainPanel(object sender, EventArgs e)
        {
            this.ShowInTaskbar = true;
            this.WindowState = WindowState.Normal;
            this.Activate();
        }

        private void exit(object sender, EventArgs e)
        {
            KillExeProcess(@"UpdateClient");
            notifyIcon.Dispose();
            Application.Current.Shutdown();
        }

        private void notifyIcon_MouseClick(object sender, WF.MouseEventArgs e)
        {
            //如果鼠标左键单击
            if (e.Button == WF.MouseButtons.Left)
            {
                this.ShowInTaskbar = true;
                this.WindowState = WindowState.Normal;
                this.Activate();
            }
        }

        private void UpdateWnd_Loaded(object sender, EventArgs e)
        {
            listBox1.Items.Add("正在检查更新...");
            
            string s = new ConnectionBase().Get(@"http://www.win7soft.com/doucontorl/justlisten/update.htm");
            if (string.IsNullOrEmpty(s))
            {
                listBox1.Items.Add("网络异常！请检查网络或者重试！");
                return;
            }
            else
            {
                Match match = Regex.Match(s, @"<td>Version:([^\""]+)</td>");
                newversion = match.Groups[1].Value;
                Match match1 = Regex.Match(s, @"<td>ReleaseDate:([^\""]+)</td>");
                newdate = match1.Groups[1].Value;
                XmlDocument doc = new XmlDocument();
                doc.Load("version.xml");
                XmlElement root = doc.DocumentElement;
                if (root.SelectSingleNode("version") != null)
                {
                    //获取 forceUpdate 节点的内容  
                    string currentversion = root.SelectSingleNode("version").InnerText;
                    if (currentversion == newversion)
                    {
                        listBox1.Items.Add("当前版本不需要更新！");
                        return;
                    }
                    else
                    {
                        //关闭应用程序
                        listBox1.Items.Add("正在关闭应用程序");
                        listBox1.Items.Add(KillExeProcess(ApplicationName));

                        Match match2 = Regex.Match(s, @"<td>Url:([^\""]+)</td>");
                        string url = match2.Groups[1].Value;
                        listBox1.Items.Add("开始下载文件,请稍等...");
                        string filename = url.Substring(url.LastIndexOf("/") + 1);
                        filepath = Environment.GetEnvironmentVariable("TEMP") + @"\" + filename;
                        listBox1.Items.Add(DownloadFile(url, filepath));
                    }
                }
                else
                    return;
            }
        }

        private string KillExeProcess(string ApplicationName)
        {
            string err = "";
            try
            {
                foreach (Process p in Process.GetProcessesByName(ApplicationName))
                    p.Kill();
                err = "应用程序进程已终止！";
            }
            catch (Exception ex)
            {
                err = "终止程序进程出错：" + ex.Message;
            }
            return err;
        }

        private string DownloadFile(string url, string filepath)
        {
            string tmp = "";
            WebClient client = new WebClient();
            try
            {
                Uri address = new Uri(url);
                if (File.Exists(filepath))
                    File.Delete(filepath);
                client.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadFileCallback);
                client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressCallback);
                client.DownloadFileAsync(address, filepath);
            }
            catch (Exception ex)
            {
                tmp = "下载更新文件出错：" + ex.Message;
            }
            return tmp;
        }

        private void DownloadProgressCallback(object sender, DownloadProgressChangedEventArgs e)
        {
            listBox1.Items.RemoveAt(listBox1.Items.Count - 1);
            listBox1.Items.Add(@"文件大小:" + e.TotalBytesToReceive / 1024f + @"KB   " +
                                @"下载进度：" + e.ProgressPercentage.ToString() + @"%");
        }

        private void DownloadFileCallback(object sender, AsyncCompletedEventArgs e)
        {
            listBox1.Items.Add("下载完成！等待解压！");
            listBox1.Items.Add("开始解压缩文件,请稍等...");
            //DirectoryInfo dinfo = new DirectoryInfo(currentfilepath);
            UnZip(filepath, currentfilepath);
        }

        private bool UnZip(string zipFile, string destFolder)
        {
            if (!File.Exists(zipFile))
                return false;

            if (!Directory.Exists(destFolder))
                Directory.CreateDirectory(destFolder);
            FileInfo fi = new FileInfo(zipFile);

            try
            {
                using (ZipInputStream zis = new ZipInputStream(fi.OpenRead()))
                {
                    ZipEntry ze;
                    while ((ze = zis.GetNextEntry()) != null)
                    {
                        string path = System.IO.Path.Combine(destFolder, ze.Name);
                        if (ze.IsDirectory)
                        {
                            Directory.CreateDirectory(path);
                        }
                        else
                        {
                            using (Stream outStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Write))
                            {
                                int size = 2048;
                                byte[] data = new byte[size];

                                while (size > 0)
                                {
                                    size = zis.Read(data, 0, data.Length);
                                    outStream.Write(data, 0, size);
                                }

                                outStream.Flush();
                            }
                        }
                    }
                    listBox1.Items.Add("解压缩完成！");

                    XmlDocument doc = new XmlDocument();
                    doc.Load("version.xml");
                    XmlElement root = doc.DocumentElement;
                    if (root.SelectSingleNode("version") != null && root.SelectSingleNode("releasedate") != null)
                    {
                        root.SelectSingleNode("version").InnerText = newversion;
                        root.SelectSingleNode("releasedate").InnerText = newdate;
                    }
                    doc.Save("version.xml");

                    File.Delete(filepath);
                    Process.Start(@"JustListen.exe");
                    Application.Current.Shutdown();
                }
            }
            catch (Exception ex)
            {
                string tmp = "解压缩出错：" + ex.Message;
                listBox1.Items.Add(tmp);
                return false;
            }

            return true;
        }

        private void image1_MouseEnter(object sender, MouseEventArgs e)
        {
            image1.Opacity = 1.0;
            BlurEffect newBlurEffect = new BlurEffect();
            newBlurEffect.Radius = 3;
            image1.Effect = newBlurEffect;
        }

        private void image1_MouseLeave(object sender, MouseEventArgs e)
        {
            image1.Opacity = 0.6;
            image1.Effect = null;
        }

        private void image2_MouseEnter(object sender, MouseEventArgs e)
        {
            image2.Opacity = 1.0;
            BlurEffect newBlurEffect = new BlurEffect();
            newBlurEffect.Radius = 3;
            image2.Effect = newBlurEffect;
        }

        private void image2_MouseLeave(object sender, MouseEventArgs e)
        {
            image2.Opacity = 0.6;
            image2.Effect = null;
        }

        private void image1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
            this.ShowInTaskbar = false;
            notifyIcon.ShowBalloonTip(3000, "更新提示", "应用程序正在后台更新", System.Windows.Forms.ToolTipIcon.Info);
        }

        private void image2_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            notifyIcon.Dispose();
            Application.Current.Shutdown();
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            notifyIcon.Dispose();
        }

        private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ButtonState == MouseButtonState.Pressed)
            {
                this.DragMove();
            }
        }
    }
}
